//
//  EditPsInformationViewController.m
//  JF_New_DYKT
//
//  Created by 陈雷 on 2017/8/31.
//  Copyright © 2017年 陈雷. All rights reserved.
//

#import "EditPsInformationViewController.h"
#import "JFSettingCell.h"
#import "JFSelectAreaB.h"
#import "EditPsMessageController.h"
#import "UINavigationController+BackButtonHandler.h"


@interface EditPsInformationViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong) UITableView *tbv;
@property (nonatomic,strong) NSArray *leftArr;
@property (nonatomic,strong) NSArray *rightArr;
@property (nonatomic,strong) UIImageView *headerImv;

@end

@implementation EditPsInformationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self baseConfig];
}

- (void)baseConfig{
    
    self.title = @"修改个人信息";
    
    self.tbv = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, KSCreenWidth, KSCreenHeight - 64) style:UITableViewStyleGrouped];
    self.tbv.delegate = self;
    self.tbv.dataSource = self;
    [self.view addSubview:self.tbv];
    
    [self.tbv registerNib:[UINib nibWithNibName:@"JFSettingCell" bundle:nil] forCellReuseIdentifier:@"JFSettingCell"];
    self.tbv.separatorColor = [UIColor colorWithHexString:@"eeeeee"];
    self.tbv.separatorInset = UIEdgeInsetsZero;
    self.tbv.backgroundColor = [UIColor colorWithHexString:@"f6f6f6"];
    self.tbv.tableFooterView = [UIView new];
    
    
    self.leftArr = @[@"头像",@"姓名",@"性别",@"个人简介",@"职业",@"地区"];
    
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == 0) {
        return 75;
    }
    return 50;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 10;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.leftArr.count;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    JFSettingCell *cell = [tableView dequeueReusableCellWithIdentifier:@"JFSettingCell" forIndexPath:indexPath];
    
    cell.leftTitleLb.text = self.leftArr[indexPath.row];
    
    
    if (indexPath.row == 0) {
        
        [cell addSubview:self.headerImv];
        [self.headerImv sd_setImageWithURL:[NSURL URLWithString:self.msgModel.LOGO] placeholderImage:[UIImage imageNamed:@"headerImgZhanWei.png"]];
    }else if (indexPath.row == 1){
        cell.rightContentLb.text = self.msgModel.NICK_NAME;
        cell.rightContentLb.tag = 2017;
    }else if (indexPath.row == 2){
        if ([self.msgModel.SEX isEqualToString:@"0"]) {
            cell.rightContentLb.text = @"女";
        }else{
            cell.rightContentLb.text = @"男";
        }
        
        cell.rightContentLb.tag = 10086;
        
    }else if (indexPath.row == 3){
    
        if (self.msgModel.USER_SIGN.length > 0) {
            cell.rightContentLb.text = self.msgModel.USER_SIGN;
        }else{
            cell.rightContentLb.text = @"主人很懒，什么也没留下...";
        }
        cell.rightContentLb.tag = 2018;
    }else if (indexPath.row == 4){
        if (self.msgModel.OCCUPATION.length > 0) {
            cell.rightContentLb.text = self.msgModel.OCCUPATION;
        }else{
            cell.rightContentLb.text = @"未填写";
        }
        cell.rightContentLb.tag = 2019;
    }else if (indexPath.row == 5){
    
        cell.rightContentLb.text = [self.msgModel.AREA stringByReplacingOccurrencesOfString:@";" withString:@" "];
        cell.rightContentLb.tag = 10087;
    }
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == 0) {
        // 跳转到相机或相册页面
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = YES;
        
        UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"更换头像" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        
        UIAlertAction *takePhotoAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
            [self presentViewController:imagePickerController animated:YES completion:^{
                
            }];
        }];
        
        UIAlertAction *photoAlbumAction = [UIAlertAction actionWithTitle:@"打开相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self presentViewController:imagePickerController animated:YES completion:^{
                
            }];
        }];
        
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        
        [alertVc addAction:takePhotoAction];
        [alertVc addAction:photoAlbumAction];
        [alertVc addAction:cancelAction];
        
        [self presentViewController:alertVc animated:YES completion:nil];
        
        
    }else if (indexPath.row == 1){
    
        EditPsMessageController *editMsgVc = [[EditPsMessageController alloc]init];
        
        editMsgVc.titleStr = @"姓名";
        editMsgVc.defaultStr = self.msgModel.NICK_NAME;
        editMsgVc.transB = ^(NSString *contentStr) {
            UILabel *lb = [self.tbv viewWithTag:2017];
            lb.text = contentStr;
            self.msgModel.NICK_NAME = contentStr;
        };
        [self.navigationController pushViewController:editMsgVc animated:YES];
        
    }else if (indexPath.row == 2){
        
        UILabel *sexLb = [self.tbv viewWithTag:10086];
        
        UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"更换头像" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        
        UIAlertAction *takePhotoAction = [UIAlertAction actionWithTitle:@"男" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            sexLb.text = @"男";
            self.msgModel.SEX = @"1";
            NSDictionary *sexDic = @{@"world":self.msgModel.SEX,
                                     @"key":@"sex",
                                     @"userId":USERID};
            [self chagePsMsg:sexDic];
            
        }];
        
        UIAlertAction *photoAlbumAction = [UIAlertAction actionWithTitle:@"女" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            sexLb.text = @"女";
            self.msgModel.SEX = @"0";
            NSDictionary *sexDic = @{@"world":self.msgModel.SEX,
                                     @"key":@"sex",
                                     @"userId":USERID};
            [self chagePsMsg:sexDic];
        }];
        
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        
        [alertVc addAction:takePhotoAction];
        [alertVc addAction:photoAlbumAction];
        [alertVc addAction:cancelAction];
        
        [self presentViewController:alertVc animated:YES completion:nil];
    }else if (indexPath.row == 3){
        
        EditPsMessageController *editMsgVc = [[EditPsMessageController alloc]init];
        
        editMsgVc.titleStr = @"个人简介";
        editMsgVc.defaultStr = self.msgModel.USER_SIGN;
        editMsgVc.transB = ^(NSString *contentStr) {
            UILabel *lb = [self.tbv viewWithTag:2018];
            lb.text = contentStr;
            self.msgModel.USER_SIGN = contentStr;
        };
        [self.navigationController pushViewController:editMsgVc animated:YES];
        
        
    }else if (indexPath.row == 4){
        
        EditPsMessageController *editMsgVc = [[EditPsMessageController alloc]init];
        
        editMsgVc.titleStr = @"职业";
        editMsgVc.transB = ^(NSString *contentStr) {
            UILabel *lb = [self.tbv viewWithTag:2019];
            lb.text = contentStr;
            self.msgModel.OCCUPATION = contentStr;
        };
        editMsgVc.defaultStr = self.msgModel.OCCUPATION;
        
        
        [self.navigationController pushViewController:editMsgVc animated:YES];
        
    }else if (indexPath.row == 5){
        __weak typeof(self) weakSelf = self;
        
        UILabel *lb = [self.tbv viewWithTag:10087];
        
        JFSelectAreaB *selectV = [[JFSelectAreaB alloc]initWithFrame:CGRectMake(0, 0, KSCreenWidth, KSCreenHeight) completeBlock:^(NSString *areaStr) {
            
            lb.text = areaStr;
            
            weakSelf.msgModel.AREA = [areaStr stringByReplacingOccurrencesOfString:@";" withString:@""];
            
            NSDictionary *areaDic = @{@"world":self.msgModel.AREA,
                                      @"key":@"area",
                                      @"userId":USERID};
            
            [weakSelf chagePsMsg:areaDic];
            
        }];
        [self.navigationController.view addSubview:selectV];
    }
    
}


- (UIImageView *)headerImv{
    
    if (!_headerImv) {
        _headerImv = [[UIImageView alloc]initWithFrame:CGRectMake(KSCreenWidth - 80, 10, 55, 55)];
        _headerImv.layer.cornerRadius = 27.5;
        _headerImv.layer.masksToBounds = YES;
        _headerImv.image = [UIImage imageNamed:@"zhanweitouxiang"];
    }
    return _headerImv;
}


- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    [picker dismissViewControllerAnimated:YES completion:nil];
    UIImage *img = info[@"UIImagePickerControllerEditedImage"];
    //对图片进行压缩处理
    img = [self imageWithImageSimple:img scaledToSize:CGSizeMake(200, 200) targetKB:100];
    
    NSData *data = UIImagePNGRepresentation(img);
    
    NSString *headerStr = [data base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed];
    
    self.headerImv.image = img;
    
    
    NSString *urlStr = [NSString stringWithFormat:@"%@user/Personal/saveHeadImage",kDomainName];
    
    NSDictionary *paraDic = @{@"imgbase64":headerStr,
                              @"userId":USERID};
    
    BaseRequest *request =  [BaseRequest sharedBaseRequest];
    
    
    __weak typeof(self) weakSelf = self;
    
    [request post:urlStr params:paraDic success:^(NSURLSessionDataTask *task, id responseObject) {
        
        
        if ([responseObject[@"code"] isEqualToString:@"1"] ) {
            
            weakSelf.msgModel.LOGO = responseObject[@"data"];
            
            [JKToast showWithText:responseObject[@"message"]];
            
        }else{
            [JKToast showWithText:responseObject[@"message"]];
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
    
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}



#pragma mark- 对图片进行压缩
- (UIImage*)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize targetKB: (NSInteger)KB
{
    // Create a graphics image context
    UIGraphicsBeginImageContext(newSize);
    
    // Tell the old image to draw in this new context, with the desired
    // new size
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    
    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // End the context
    UIGraphicsEndImageContext();
    
    // Return the new image.
    NSData *data = UIImageJPEGRepresentation(newImage, 1);
    
    //kb为0时没有设定图片必须小于某个数
    if (KB != 0) {
        while (data.length/1024 > KB) {
            
            //1.改变size的方法压缩
            // Create a graphics image context
            newSize = CGSizeMake(newSize.width*.8, newSize.height*.8);
            UIGraphicsBeginImageContext(newSize);
            
            // Tell the old image to draw in this new context, with the desired
            // new size
            [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
            
            // Get the new image from the context
            newImage = UIGraphicsGetImageFromCurrentImageContext();
            
            // End the context
            UIGraphicsEndImageContext();
            
            data = UIImageJPEGRepresentation(newImage, 1);
            
        }
    }
    
    return newImage;
}


#pragma mark- 修改个人信息
- (void)chagePsMsg:(NSDictionary *)paramDic{

    
    NSString *urlStr = [NSString stringWithFormat:@"%@user/Personal/saveBaseInfo",kDomainName];
    
    BaseRequest *request =  [BaseRequest sharedBaseRequest];
    [request post:urlStr params:paramDic success:^(NSURLSessionDataTask *task, id responseObject) {
        
        if ([responseObject[@"code"] isEqualToString:@"1"] ) {
            
            [JKToast showWithText:responseObject[@"message"]];
        }else{
            [JKToast showWithText:responseObject[@"message"]];
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];

}


@end

